package code.example.base.util.concurrent.lock.memory.visval;

import code.example.base.util.concurrent.lock.Counter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *   不使用锁，计算结果<10000,原因：内存不可见，引起的线程安全问题
 *
 */
public class TestMemoryVisible {
    Counter counter = new Counter();
    public  void addCount(){

        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            }catch (Exception e){}

           synchronized (this) {
               int count = counter.getCount();
                int newCount = count + 1;
                System.out.println(""+Thread.currentThread().getName()+":"+newCount);
                counter.setCount(newCount);
         }
        }
    }

    public void readCount(){
        while(true){
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            }catch (Exception e){}
            long count = counter.getCount();
            System.out.println("count-result:"+count);
        }
    }
    public void test(){
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for(int i=0;i<1000;i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                        addCount();
                    }

            });
        }
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                readCount();
            }

        });

        try {
            executorService.shutdown();
            executorService.awaitTermination(100, TimeUnit.SECONDS);
        }catch (Exception e){

        }
        System.out.println(counter.getCount());
    }

    public static void main(String args []){
        new TestMemoryVisible().test();
    }
}
